package com.eh.excel;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * Created by David Li on 2016/11/24.
 */
public class AbstractExcelHandler implements ExcelHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void write(WritableExcelEvent excelEvent) {
        throw new RuntimeException("不可写");
    }

    @Override
    public List read(ReadableExcelEvent excelEvent) {
        throw new RuntimeException("不可读");
    }

    protected Workbook getWorkbook(ExcelVersion excelVersion) throws IOException {
        Workbook workbook = null;
        switch (excelVersion) {
            case HSSF:
                workbook = new HSSFWorkbook();
                break;
            case XSSF:
                workbook = new XSSFWorkbook();
                break;
        }
        return workbook;
    }

    protected Workbook getWorkbook(String filePath) {
        Workbook workbook = null;
        try {
            FileInputStream is = new FileInputStream(filePath);
            //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
            if (filePath.endsWith(".xls")) {
                //2003
                return new HSSFWorkbook(is);
            } else if (filePath.endsWith("xlsx")) {
                //2007
                return new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            logger.info(e.getMessage());
        }
        return workbook;
    }

    protected String getPostfix(ExcelVersion excelVersion) {
        String postfix = null;
        switch (excelVersion) {
            case HSSF:
                postfix = ".xls";
                break;
            case XSSF:
                postfix = ".xlsx";
                break;
        }
        return postfix;
    }
}
